//
//  TableViewContorollerSectionedByAlphabets.m
//  MantuPlay
//
//  Created by Markus Sintonen on 14.8.2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "TableViewContorollerSectionedByAlphabets.h"
#import "TrackDatabase.h"
#import "DBIndex.h"
#import "NSArrayExtensions.h"
#import "UITableViewExtensions.h"

#define NUM_OF_ITEMS_TO_SHOW_SECTIONS 30

@implementation TableViewContorollerSectionedByAlphabets

@synthesize theTableView, dataSource;

- (id)initWithDataSource:(id<DatabaseObjectDataSource>)theDataSource {
	if ((self = [super init])) {
		theTableView = nil;
		
		self.dataSource = theDataSource;

		self.title = [dataSource name];
		self.navigationItem.title = [dataSource navigationBarName];
	}
	return self;
}

- (void)loadView {
	[dataSource loadData];

	/*if([dataSource showNowPlayingButton]) {
		UIButton *nowPlayingButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 64.0, 30.0)];
		nowPlayingButton.adjustsImageWhenHighlighted = NO;
		[nowPlayingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NowPlayingButtonUp" ofType:@"png"]] forState:UIControlStateNormal];
		[nowPlayingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NowPlayingButtonDown" ofType:@"png"]] forState:UIControlStateHighlighted];
		UIBarButtonItem *nowPlayingButtonItem = [[UIBarButtonItem alloc] initWithCustomView:nowPlayingButton];
		self.navigationItem.rightBarButtonItem = nowPlayingButtonItem;
		[nowPlayingButton release];
		[nowPlayingButtonItem release];
	}*/

	UITableView *tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain];
	
	tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
	
	tableView.delegate = self;
	tableView.dataSource = self;
	
	tableView.sectionIndexMinimumDisplayRowCount = 10;
	tableView.rowHeight = [dataSource rowHeight];
	
	self.theTableView = tableView;
	self.view = tableView;
	[tableView release];
	
	if([self showTableSectioned]) {
		objectsByInitialLetter = [[NSDictionary alloc] initWithDictionary:[self dictionaryOfObjectsByInitialLetter]];
		
		NSArray *tempInitialLetters = [[objectsByInitialLetter allKeys] sortedArrayUsingSelector:@selector(compareFirstCharWithAlphabetsHighestOrder:)];
		initialLetters = [[NSArray alloc] initWithArray:tempInitialLetters];
	}
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	id theViewController = nil;
	if([dataSource respondsToSelector:@selector(tableView:dataSourceForSelectedObject:atIndexPath:)]) {
		id<DatabaseObjectDataSource> dataSourceForSelectedRow;
		if([dataSource extraRowAtTop] && [tableView isFirstCellAtIndexPath:indexPath])
			dataSourceForSelectedRow = [dataSource tableView:tableView dataSourceForSelectedExtraRowAtTopIndexPath:indexPath];
		else if([dataSource extraRowAtBottom] && [tableView isLastCellAtIndexPath:indexPath])
			dataSourceForSelectedRow = nil;
		else
			dataSourceForSelectedRow = [dataSource tableView:tableView dataSourceForSelectedObject:[self objectAtIndexPath:indexPath] atIndexPath:indexPath];
		
		if(!dataSourceForSelectedRow) return;
		
		theViewController = [[TableViewContorollerSectionedByAlphabets alloc] initWithDataSource:dataSourceForSelectedRow];
	}
	else if([dataSource respondsToSelector:@selector(tableView:viewControllerForSelectedObject:atIndexPath:)]) {
		if([dataSource extraRowAtTop] && [tableView isFirstCellAtIndexPath:indexPath])
			return; //ADD SHUFFLE FUNCTION
		else if([dataSource extraRowAtBottom] && [tableView isLastCellAtIndexPath:indexPath])
			return;
		else
			theViewController = [dataSource tableView:tableView viewControllerForSelectedObject:[self objectAtIndexPath:indexPath] atIndexPath:indexPath];
	}
	else return;

	// push the element view controller onto the navigation stack to display it
	[[self navigationController] pushViewController:theViewController animated:YES];
	[theViewController release];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	if([dataSource extraRowAtTop] && [tableView isFirstCellAtIndexPath:indexPath]) 
		return [dataSource tableView:tableView cellForExtraRowAtTopIndexPath:indexPath];
	else if([dataSource extraRowAtBottom] && [tableView isLastCellAtIndexPath:indexPath]) 
		return [dataSource tableView:tableView cellForExtraRowAtBottomIndexPath:indexPath];
	else 
		return [dataSource tableView:tableView cellForObject:[self objectAtIndexPath:indexPath] atIndexPath:indexPath];
}

-(id)objectAtIndexPath:(NSIndexPath*)indexPath {
	if([dataSource extraRowAtTop] && [theTableView isFirstCellAtIndexPath:indexPath])
		return nil;
	if([dataSource extraRowAtBottom] && [theTableView isLastCellAtIndexPath:indexPath])
		return nil;
	
	id dbObject;
	if(objectsByInitialLetter) {
		NSString *key = [initialLetters objectAtIndex:indexPath.section - (int)[dataSource extraRowAtTop]];
		dbObject = [[objectsByInitialLetter objectForKey:key] objectAtIndex:indexPath.row];
	} else {
		dbObject = [dataSource.databaseObjectArray objectAtIndex:indexPath.row - (int)[dataSource extraRowAtTop]];
	}
	
	return dbObject;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	if(objectsByInitialLetter) 
		return [objectsByInitialLetter count] + (int)[dataSource extraRowAtTop];
	else 
		return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if(objectsByInitialLetter) {
		if([dataSource extraRowAtTop] && section == 0) 
			return 1;
		
		int numOfRowsInSection = [[objectsByInitialLetter objectForKey:[initialLetters objectAtIndex:section - [dataSource extraRowAtTop]]] count];
		if(section == ([theTableView numberOfSections] - 1)) 
			numOfRowsInSection += (int)[dataSource extraRowAtBottom];
		
		return numOfRowsInSection;
	} else {
		return [self numberOfItems] + (int)[dataSource extraRowAtTop] + (int)[dataSource extraRowAtBottom];
	}
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if([dataSource extraRowAtTop] && section == 0) 
		return nil;
	else
		return [initialLetters objectAtIndex:section - (int)[dataSource extraRowAtTop]];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
	return initialLetters;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
	return index + (int)[dataSource extraRowAtTop];
}


-(NSDictionary*)dictionaryOfObjectsByInitialLetter {
	NSMutableDictionary *tempObjectsAlphabetically = [[NSMutableDictionary alloc] initWithCapacity:30];
	NSArray *objectArray = dataSource.databaseObjectArray;
	for(id object in objectArray) {
		[self addObject:object toAlphabetDictionary:tempObjectsAlphabetically];
	}
	return (NSDictionary*)[tempObjectsAlphabetically autorelease];
}

-(void)addObject:(id)obj toAlphabetDictionary:(NSMutableDictionary*)dict {
	NSString *strInitialLetter = [[((GenericDatabaseObject*)obj).title substringToIndex:1] capitalizedString];
	
	NSString *key = [self keyFromInitialLetter:strInitialLetter];
	
	if(NSMutableArray *existingArray = [dict valueForKey:key]) {
		[existingArray addObject:obj];
	} else {
		NSMutableArray *tempArray = [NSMutableArray array];
		[dict setObject:tempArray forKey:key];
		[tempArray addObject:obj];
	}
}

-(NSString*)keyFromInitialLetter:(NSString*)letter {
	const char *initialLetter = [letter UTF8String];
	if(isalpha(initialLetter[0])) 
		return letter;
	else
		return @"#";
}

-(unsigned int)numberOfItems {
	return [dataSource.databaseObjectArray count];
}
-(BOOL)showTableSectioned {
	if(!dataSource.showSectioned) 
		return NO;
	else if([self numberOfItems] > NUM_OF_ITEMS_TO_SHOW_SECTIONS) 
		return YES;
	else 
		return NO;
}

-(void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[dataSource loadData];
}
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
	[dataSource unloadData];
}

- (void)didReceiveMemoryWarning {
	[[TrackDatabase sharedTrackDatabase] clearDatabaseCachedStatements];
    [super didReceiveMemoryWarning];
}


- (void)dealloc {
	theTableView.delegate = nil;
	theTableView.dataSource = nil;
	[objectsByInitialLetter release];
	[theTableView release];
	[initialLetters release];
	[dataSource release];
    [super dealloc];
}


@end
